<!--
 * @Author: 1453937336@qq.com 1453937336@qq.com
 * @Date: 2024-04-16 12:04:21
 * @LastEditors: 1453937336@qq.com 1453937336@qq.com
 * @LastEditTime: 2024-07-09 22:53:02
 * @FilePath: \company_hris\src\components\itfor-tree\index.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%
-->
<template>
  <div class="itforTree">
    <a-row>
      <a-col :span="20" @click="topTree" style="display: flex;align-items: center;">
        <svg-icon name="company" width="20" height="20" />
        <span style="margin-left: 8px;cursor:pointer;font-weight: bold" :class="ifTree ? '' : 'treeTop'">{{ companyName
          || props.menuList[0]?.name }}</span>
      </a-col>
      <a-col :span="4" style="display: flex; justify-content: flex-end;">
        <a-dropdown v-model:open="dropdownVisible">
          <i class="fa fa fa-angle-down fa-2x" @click.prevent />
          <template #overlay>
            <a-menu class="menu-list" @click="handleMenuClick">
              <a-menu-item key="search" v-if="menuList?.length > 10">
                <a-input v-model:value="menuValue" :placeholder="`${$t('search')}...`" @change="menuInputBlur">
                  <template #prefix>
                    <SearchOutlined />
                  </template>
                </a-input>
              </a-menu-item>
              <a-menu-item v-for="(item, index) in menuList" :key="index" @click="onSwitch(item.id)">{{ item.name
                }}</a-menu-item>
            </a-menu>
          </template>
        </a-dropdown>
      </a-col>
      <a-col :span="24" style="display: flex;justify-content: flex-end;margin-top: 10px;align-items: center;">
        <span style="font-size: 12px;">{{ $t('岗位类型') }} :</span>
        <a-select :getPopupContainer="(triggerNode) => triggerNode.parentNode" ref="select" v-model:value="positionTypeVule" @change="positionTypechange" style="width: 50%;">
          <a-select-option v-for="(item, index) in props.positionTypeList" :value="item.dictData">{{ isCn ? item.descZh
            :
            isArabic ? item.descAr : item.dictDesc}}</a-select-option>
        </a-select>
      </a-col>
    </a-row>
    <a-divider />
    <div class="boxTree">
      <a-tree v-if="refresh && list?.length" :tree-data="list" showIcon v-model:selectedKeys="treeCurrentKey"
        v-model:checkedKeys="checkedKeys" v-model:expandedKeys="expandedKeys" :class="isArabic ? 'arabic' : 'default'"
        @select="treeCheck" :fieldNames="{
          // children: 'children',
          // title: 'shortNameEn',
          key: 'id'
        }">
        <template #title="{ shortNameZh, shortNameEn, shortNameAr, nameEn, nameAr, nameZh, unitTypeIcon, uuid, children }">
          <div style="display: flex;align-items: center;" :style="{ 'font-weight': children?.length > 0 ? '500' : '' }">
            <svg-icon style="margin-top: 2px; color: currentColor;" :name="unitTypeIcon" />
            <span class="treeName" :title="isCn && nameZh ? nameZh : isArabic && nameAr ? nameAr : nameEn">
              {{ isCn && nameZh ? nameZh : isArabic && nameAr ? nameAr : nameEn }}
            </span>
          </div>
        </template>

        <template #switcherIcon="{ switcherCls, defaultIcon }">
          <i :class="switcherCls" class="fa fa-angle-up up" />
        </template>
      </a-tree>
    </div>

  </div>
</template>
<script setup>
import { SearchOutlined } from "@ant-design/icons-vue";
import { reactive, nextTick, ref, watch, defineProps, onMounted, getCurrentInstance } from "vue";
import { useStore } from "vuex";
import { useLanguage } from "@/hooks/index";
const { isEn, isCn, isArabic } = useLanguage();
const store = useStore();
const emits = defineEmits(['treeEmint', 'companyIdChange', 'positionTypeChange'])
const props = defineProps({
  menuList: { type: Array, default: [] },
  treeData: { type: Array, default: [] },
  positionTypeList: { type: Array, default: [] },
  id: { type: String, default: "" },
  parentId: { type: String, default: "" }
});
const checkedKeys = ref([]);
const expandedKeys = ref([])
const companyName = ref(null)
const menuList = ref([])
watch(() => props.menuList,
  (newVal) => {
    companyName.value = props.menuList[0].name
    menuList.value = newVal
  },
  {
    flush: 'post',
  }
);
const list = ref([])
const refresh = ref(true)
const refreshTree = () => {
  refresh.value = false
  nextTick(() => {
    refresh.value = true
  })
}

const treeCurrentKey = ref(null)

watch(() => props.parentId,
  (newVal) => {
    checkedKeys.value = newVal
    // // consolelog('treeCurrentKey.value', checkedKeys.value);
  },
  {
    flush: 'post',
    immediate: true
  }
);

const positionTypeVule = ref('0')
const positionTypechange = (val) => {
  positionTypeVule.value = val
  emits('positionTypeChange', Number(positionTypeVule.value))
}

const treeList = ref([])
const flattenTree = (tree, parentId = null) => {
  let flattened = [];
  for (let node of tree) {
    const cloned = { ...node, parentId };
    delete cloned.children; // 删除children属性，以便可以直接添加到结果数组中
    flattened.push(cloned);
    if (node.children && node.children.length > 0) {
      // 递归处理子节点
      flattened = flattened.concat(flattenTree(node.children, node));
    }
  }
  return flattened;
}
watch(() => props.treeData,
  (newVal) => {
    list.value = newVal
    treeList.value = flattenTree(newVal)
    expandedKeys.value = treeList.value.map(item => item.id)
    // // consolelog('defaultExpandedKeys.value', expandedKeys.value);
  },
  {
    flush: 'post',
    deep: true,
    immediate: true
  }
);

const rodList = () => {
  topTree()
}
const ifTree = ref(false)
// top 公司切换
const onSwitch = (id) => {
  let companyObj = props.menuList.find(item => item.id === id)
  companyName.value = companyObj.name
  // 刷新tree
  topTree()
  emits('companyIdChange', companyObj)
}

// tree 选中

const treeCheck = (v, selectedNodes) => {
  console.log('tree选中', v)
  if (!v) ifTree.value = false
  else ifTree.value = true
  emits('treeEmint', ifTree.value, selectedNodes.selectedNodes[0])
}

const topTree = () => {
  nextTick(() => {
    ifTree.value = false
    treeCurrentKey.value = null
    checkedKeys.value = null
    emits('treeEmint', ifTree.value)
  })
  refreshTree()
}
const dropdownVisible = ref(false)
const menuValue = ref('')
const handleMenuClick = (e) => {
  console.log(e);
  if (e.key !== 'search') {
    dropdownVisible.value = false;
    menuValue.value = null
    menuList.value = props.menuList
  } else {
    dropdownVisible.value = true;
  }
}
const menuInputBlur = debounce(() => {
  if (menuValue.value) {
    menuList.value = menuList.value.filter((item) =>
      item.name?.toLowerCase().includes(menuValue.value?.toLowerCase())
    );
  } else {
    menuList.value = props.menuList
  }
}, 1000);
defineExpose({
  rodList
});
</script>
<style>
.default .ant-tree-switcher {
  position: absolute;
  right: 0;
}

.arabic .ant-tree-switcher {
  position: absolute;
  left: 0;
}
</style>
<style lang="scss" scoped>
.itforTree {
  width: 100%;
  padding: 16px;
  // background-color: #f2f2f2;
}

.boxTree {
  padding-bottom: 48px;
  height: 100vh;
  overflow-y: scroll;
}

.boxTree::-webkit-scrollbar {
  display: none;
}

.treeName {
  // font-weight: 500;
  margin-right: 5px;
  margin-left: 5px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  font-size: 12px;
  width: 260px;
}

.treeTop {
  color: #ff6700;
}

.a-icon--right {
  color: #cec0c4;
}

.margin-t-16 {
  margin-top: 16px;
}

.title {
  width: 100%;
}

.fa-angle-down {
  color: #a7b1c2;
}

.up {
  color: #a7b1c2;
  font-size: 20px;
}

.menu-list {
  max-height: 500px;
  min-width: 100px;
  text-align: left;
  overflow-y: scroll;

  &::-webkit-scrollbar {
    display: none
  }
}

::v-deep {
  .ant-tree .ant-tree-list-holder-inner {
    background-color: #f2f2f2;
  }

  .ant-tree .ant-tree-treenode {
    width: 100%;
    border-bottom: 1px solid #d9d9d9;
  }

  // .ant-tree span.ant-tree-switcher.ant-tree-switcher_close .ant-tree-switcher-icon{
  //   transform: scale(0.83333333) rotate(-180deg);
  // }
  // .ant-tree .ant-tree-node-content-wrapper.ant-tree-node-selected {
  //   background-color: #f2f2f2;
  //   color: #ff6700;
  // }
  .ant-tree .ant-tree-node-content-wrapper:hover {
    background-color: #f2f2f2;
    color: #ff6700;
  }

  .ant-tree .ant-tree-switcher {
    line-height: 30px;
  }

  .ant-tree .ant-tree-switcher .ant-tree-switcher-icon {
    font-size: 20px;
  }

  .ant-tree span.ant-tree-switcher.ant-tree-switcher_close .ant-tree-switcher-icon {
    transform: rotate(-180deg);
  }

  .ant-tree .ant-tree-node-content-wrapper.ant-tree-node-selected {
    background-color: #f2f2f2;
    color: #ff6700;
  }

  .ant-tree .ant-tree-switcher .ant-tree-switcher-icon {
    font-size: 20px;
  }

  // 全局样式修改回来
  .ant-input-affix-wrapper {
    border: 1px solid #dadada !important;
    padding: 6px !important;
  }

  .ant-input {
    border-bottom: none !important;
  }

  // .ant-select .ant-select-selector {
  //   border: 1px solid #dadada !important;
  // }
}
</style>
